<?php
/**
 * 质检控制器
 * Created by PhpStorm.
 * User: poptser@foxmail.com
 * Date: 2018/3/27
 * Time: 17:00
 */
namespace App\Http\Controllers\Sorting;

use App\Http\Controllers\ApiController;
use App\Services\Sorting\QualityService;
use App\Services\Sorting\RefundService;
use App\Services\Sorting\ScanService;
use App\Services\Sorting\SortingService;
use App\Services\SortingWeb\OrderService;
use App\Services\SortingWeb\ToolService;
use App\Services\Warehouse\ConsignmentNoteService;
use Illuminate\Http\Request;
use App\Services\Orders\OrderService as Order;
use Illuminate\Support\Facades\Auth;
use App\Services\SortingWeb\OrderService as SortingOrder;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class QualityController extends ApiController{

    public $sortingService;
    public $order;          //主order service
    public $qualityService;
    public $toolService;    //辅助工具 service
    public $sortingOrder;    //辅助工具 service
    public $ConsignmentNoteService;
    public $refundService;
    public $orderService;

    public $userId;
    public $wid;
    public $userName;

    public function __construct(SortingOrder $sortingOrder,Order $order,
                                QualityService $qualityService,
                                ToolService $toolService,
                                OrderService $orderService,
                                ConsignmentNoteService $consignmentNoteService,
                                SortingService $sortingService,
                                RefundService $refundService){
        $isLogion = Auth::guard('sorting')->check();
        if(!$isLogion){
            $this->returnErr("api_token 不存在或已过期");
        }else{
            $this->userId = Auth::guard('sorting')->id();
            if($this->checkUserType(7,$this->userId)){
                $this->returnErr("您没有访问此接口得权限");
            }else{
                $this->refundService = $refundService;
                $this->sortingOrder = $sortingOrder;
                $this->order = $order;
                $this->orderService = $orderService;
                $this->qualityService = $qualityService;
                $this->toolService = $toolService;
                $this->ConsignmentNoteService=$consignmentNoteService;
                $this->sortingService = $sortingService;
                $this->userName = $this->toolService->getNameById($this->userId);
                $this->wid = $this->toolService->getUserWid($this->userId);
            }
        }

//        $this->sortingOrder = $sortingOrder;
//        $this->order = $order;
//        $this->qualityService = $qualityService;
//        $this->toolService = $toolService;
//        $this->ConsignmentNoteService=$consignmentNoteService;
//        $this->sortingService = $sortingService;


    }


    /**
     * 打印分待单
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function orderBagsPrint(Request $request){



        $orderId = $request->orderId;     //订单ID
        $bagInfo = $request->bagInfo;     //分袋数 常温0 冷藏1 冷冻2

        $typeNameList = array("常","冻","藏");

        $str= "";
        $order_bag_info = array();
        $bag_array = explode(",",$bagInfo);
        $allBag = 0;
        foreach ($bag_array as $value){
            $allBag +=$value;
        }


        $current_num = 1;
        foreach ($bag_array as $key=>$value){
            if($key==1){
                $type = 2;
            }elseif($key==2){
                $type = 1;
            }else{
                $type = $key;
            }
            if($value>0){
                for($i=0;$i<$value;$i++){
                    $bag_one_info = array(
                        "all"=> $allBag,
                        "current"=> $current_num,
                        "type"=> $type,  //常温0 冷藏1 冷冻2
                        "is_scan"=> 0
                    );
                    $current_num ++;
                    $order_bag_info[] = $bag_one_info;
                }
            }
            $str .=$typeNameList[$key].$value;
        }
        Cache::put("order_bag_".$orderId,$order_bag_info,43200);
            //S("order_bag_".$orderId,$order_bag_info,43200);  //订单分袋信息保存一个月



        $is_db = DB::selectOne("SELECT * FROM sdx_order_info_ext WHERE order_id = ".$orderId);
        if($is_db){
            DB::update("UPDATE sdx_order_info_ext SET bag_num =".$allBag." WHERE order_id=".$orderId);
        }else{
            DB::insert("INSERT sdx_order_info_ext (order_id,bag_num) VALUES (".$orderId.",".$allBag.")");
        }


        $order_info = DB::table("order_info")
            ->where("order_id",$orderId)->first(['order_status','shipping_status','pay_status']);

        //dump($a);
        $statusDescription = '打印质检单，总数：'.$allBag.", ".$str;
        $dataAction['order_status'] = $order_info->order_status;
        $dataAction['shipping_status'] = $order_info->shipping_status;
        $dataAction['pay_status'] = $order_info->pay_status;
        $dataAction['action_user'] = $this->toolService->getNameById($this->userId);
        $dataAction['order_id']=$orderId;
        $dataAction['action_note']=$statusDescription." [ SortingApp ]";;
        $dataAction['log_time']=gm_time();
        $dataAction['user_id']=$this->userId;

        $this->order->addOrderAction($dataAction);
        $this->toolService->recordLogistics($orderId,$order_info->shipping_status,$statusDescription);

        return $this->success(null);
    }



    /**
     * 获取商品列表
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getGoodsList(Request $request){
        $cameraInput = $request->cameraInput;
        $actionType = $request->actionType; #1质检模式 2回仓模式
        if(empty($cameraInput)){
            return $this->failed("参数错误");
        }
        $ScanService = new ScanService();

        $filter = $ScanService->convertFilter($cameraInput);
        $orderId = $ScanService->getOrderId($filter);
        if(empty($orderId)){
            return $this->failedReturn("未找到此订单：".$cameraInput);
        }
        $orderStatus = $this->order->getOrderById($orderId,
            ['distribution_company_id','wdr_id','sign_building','address',
                'district','mobile','consignee','best_time_start',
                'best_time','quality_id','order_sn','order_status',
                'shipping_status','pay_status','freeze_status','outgo']
        );

        if($orderStatus['freeze_status']>0){
            return $this->failedReturn("无法质检：已提交问题单");
        }

        if(in_array($orderStatus['pay_status'],[2,3])){

            if($actionType==1){
                //质检模式
                $goodsList = $this->qualityService->getGoodsListNorm($orderId);
            }else{
                #回仓模式
                if($orderStatus['shipping_status']==2){
                    //收货确认
                    $goodsList = $this->qualityService->getGoodsListLack($orderId);
                }else{
                    $goodsList = $this->qualityService->getGoodsListNorm($orderId);
                }
            }

            $reData['orderId'] = $orderId;
            $reData['orderSn'] = $orderStatus['order_sn'];
            $reData['bestTime'] = date('Y-m-d H:i',$orderStatus['best_time_start'])."-".date('H:i',$orderStatus['best_time']); //预期送达时间
            $reData['consignee'] = $orderStatus['consignee'];
            $reData['mobile'] = $orderStatus['mobile'];
            $reData['signBuilding'] = $orderStatus['sign_building'];
            $reData['address'] = DB::table("region")->where("region_id",$orderStatus['district'])->value("region_name").$orderStatus['address'];
            $reData['companyName'] = DB::table("distribution_company")->where("id",$orderStatus['distribution_company_id'])->value("lite_name");
            $reData['companyNameId'] = $orderStatus['distribution_company_id'];
            $orderRegion = DB::table("warehouse_deliver_region")->where("id",$orderStatus['wdr_id'])->first();
            $reData['orderRegion'] = DB::table("zoning_cate")->where("id",$orderRegion->zoning_id)->value("name")." ".$orderRegion->name;

            $reData['freeSingle'] = DB::table("order_info_free_single")->where("order_id",$orderId)->count();

            if(empty($reData['companyName'])){
                $reData['companyName'] = "自";
            }

            if($orderStatus['quality_id']>0){
                $reData['qualityStatus'] = 1;
            }else{
                $reData['qualityStatus'] = 0;
            }
            $reData['goodsList'] = $goodsList;
            return $this->success($reData);
        }else{
            return $this->failedReturn("订单未付款/全部退款");
        }


    }


    /**
     * 商品质量确认
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function goodsConfirm(Request $request){

        $orderId = $request->orderId;


        $orderInfo = $this->order->getOrderById($orderId,['*']);

        if($orderInfo['shipping_status']==5&&$orderInfo['freeze_status']==0){

            $updateDate['quality_id'] = $this->userId;
            $updateDate['quality_time'] = gm_time();
            //DB::enableQueryLog();
            DB::table('order_info')->where([
                ["order_id","=",$orderId]
            ])->update($updateDate);

            $orderStatus = $this->sortingOrder->getOrderStatus($orderId);
            $dataAction['order_status'] = $orderStatus->order_status;
            $dataAction['shipping_status'] = $orderStatus->shipping_status;
            $dataAction['pay_status'] = $orderStatus->pay_status;
            $dataAction['action_user'] = $this->toolService->getNameById($this->userId);
            $dataAction['order_id']=$orderId;
            $dataAction['action_note']='商品质量已确认'." [ SortingApp ]";;
            $dataAction['log_time']=gm_time();
            $dataAction['user_id']=$this->userId;
            $this->order->addOrderAction($dataAction);
            $this->toolService->recordLogistics($orderId,$orderStatus->shipping_status,'商品质量已确认');
            //审核发货单
            if(!empty($orderInfo['k3cn_sn'])){
                $this->ConsignmentNoteService->ConsignmentNoteSubmitAndAudit([$orderInfo['k3cn_sn']]);
            }

            return $this->success(null);
        }else{
            return $this->failedReturn("未完成配货/已提交问题单");
        }
    }

    /**
     * 获取未质检列表
     * Author:poptser@foxmail.com
     */
    public function QualityGetQualityList(){
        //return $this->wid;
        $getUnQualityList = $this->qualityService->getUnQualityList($this->wid);
        return $this->success($getUnQualityList);
    }


    /**
     * 商品回仓操作【退货仓调到次品/门店仓】
     * Author:poptser@foxmail.com
     * @param $request
     * @return mixed
     */
    public function goodsToBack(Request $request){
        $orderId = $request->orderId;
        $goodsListJosn = $request->goodsList;
        $goodsList = json_decode($goodsListJosn,true);

        if(!$goodsList){
            return $this->failedReturn("Json 数据异常");
        }

        $toNormList = [];
        $toPoorList = [];

        foreach ($goodsList as $value){
            if($value['poorNum']>0){
                $toPoorList[] = [
                    "goodsSn"=>$value['goodsSn'],
                    "operationsNum"=>$value['poorNum']
                ];
            }
            if($value['normalNum']>0){
                $toNormList[] = [
                    "goodsSn"=>$value['goodsSn'],
                    "operationsNum"=>$value['normalNum']
                ];
            }
        }

        $orderStatus = $this->order->getOrderById($orderId,
            ['distribution_company_id','wdr_id','sign_building','address',
                'district','mobile','consignee','best_time_start',
                'best_time','quality_id','order_sn','order_status',
                'shipping_status','pay_status','freeze_status','outgo']
        );
//        dump($orderStatus->distribution_company_id);
//        exit();
        if($orderStatus->quality_id>0&&$orderStatus->outgo==0){
            //已质检&未出仓
            #判断是否是回仓单
            $isBack = DB::selectOne("SELECT order_id FROM sdx_order_action WHERE action_note LIKE '%已回仓%' AND order_id=".$orderId);
            if(empty($isBack)){
                //未回仓
                if($orderStatus->shipping_status!=2){
                    //未确认收货，执行退货处理
                    $refundStatus = $this->refundService->refundGoods($orderId,$goodsList,
                        4,false,"质检员直接回仓",$this->userId,$this->wid,
                        0,6);
                    if($refundStatus!==true){
                        return $this->failedReturn("订单退货处理出错:".$refundStatus);
                    }
                }

            }

            $ToolService = new ToolService();
            $orderStatus = $this->orderService->getOrderStatus($orderId);
            $data['order_status'] = $orderStatus->order_status;
            $data['shipping_status'] = $orderStatus->shipping_status;
            $data['pay_status'] = $orderStatus->pay_status;
            $dataAction['action_user'] = $ToolService->getNameById($this->userId);
            $dataAction['order_id']=$orderId;
            $dataAction['action_note']='质检未出仓订单，全部退款且调仓操作 [ Sorting ]';
            $dataAction['log_time']=gm_time();
            $dataAction['user_id']=$this->userId;
            $this->order->addOrderAction($dataAction);
        }


        if(count($toNormList)>0){
            $result = $this->qualityService->setGoodsToWarehouse($orderId,$toNormList,1,$this->userName);
            //return $result;
            Log::notice(json_encode($toNormList));
            if(!is_array($result)){
                $result_array = json_decode($result,true);
                return $this->failedReturn("正常调仓处理:".$result_array['status']);
            }
        }

        if(count($toPoorList)>0){
            $result = $this->qualityService->setGoodsToWarehouse($orderId,$toPoorList,2,$this->userName);
            //return $result;
            Log::notice(json_encode($toPoorList));
            if(!is_array($result)){
                $result_array = json_decode($result,true);
                return $this->failedReturn("次品调仓处理:".$result_array['status']);
            }
        }

        return $this->success(null,"成功");

    }
}